package com.tonghe.aspect;

import com.alibaba.fastjson.JSON;
import com.tonghe.annotation.SystemLog;
import com.tonghe.domain.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Date:2022/4/9- 04- 09- 21:10
 * 切面类
 **/

@Component
@Slf4j
@Aspect // 切面类
public class LogAspect {

    // 确定切点
    @Pointcut("@annotation(com.tonghe.annotation.SystemLog)")
    public void pt(){

    }

    // 定义通知方法
    @Around("pt()") // 环绕通知
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object ret;
        try {
            handleBefore(joinPoint);
            ret = joinPoint.proceed();
            handleAfter(ret);
        } finally {
            log.info("======End======"+System.lineSeparator()); // 系统的换行符，兼容window与unix
        }
        return ret;
    }

    private void handleBefore(ProceedingJoinPoint joinPoint) {

        // 多态
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //
        SystemLog systemLog = getSystemLog(joinPoint);

        log.info("======Start======");
        log.info("URL           : {}", request.getRequestURL());
        log.info("BusinessName  : {}", systemLog.businessName());
        log.info("HTTP Method   : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("class Method  : {}.{}",
                joinPoint.getSignature().getDeclaringTypeName(),
                ((MethodSignature)joinPoint.getSignature()).getName());
        log.info("IP            : {}", request.getRemoteHost());
        log.info("Request Args  : {}", JSON.toJSONString(joinPoint.getArgs()));

    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {

        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        // 疯狂调试
        SystemLog systemLog = methodSignature.getMethod().getAnnotation(SystemLog.class);
        return systemLog;

    }

    private void handleAfter(Object ret) {
        log.info("Response      : code：{},msg:{}", ((ResponseResult) ret).getCode().toString(),((ResponseResult) ret).getMsg());
    }


}
